const db = require('../config/database')
const { success, error } = require('../utils/responseHelper')

const questionController = {
  // 获取考试题目列表
  async getQuestions(req, res, next) {
    try {
      const { examId } = req.params
      const { role } = req.user

      // 检查考试是否存在
      const [exams] = await db.execute('SELECT * FROM exams WHERE id = ?', [
        examId,
      ])
      if (exams.length === 0) {
        return error(res, '考试不存在', 404)
      }

      let query =
        'SELECT * FROM questions WHERE exam_id = ? ORDER BY order_num ASC, id ASC'

      // 如果是学生且考试已开始，不返回正确答案
      if (role === 'student') {
        const exam = exams[0]
        const now = new Date()
        const startTime = new Date(exam.start_time)
        const endTime = new Date(exam.end_time)

        if (now >= startTime && now <= endTime) {
          query = `SELECT id, exam_id, type, title, content, options, score, order_num 
                   FROM questions WHERE exam_id = ? ORDER BY order_num ASC, id ASC`
        }
      }

      const [questions] = await db.execute(query, [examId])

      success(res, questions)
    } catch (err) {
      next(err)
    }
  },

  // 创建题目
  async createQuestion(req, res, next) {
    try {
      const { examId } = req.params
      const {
        type,
        title,
        content,
        options,
        correct_answer,
        score,
        order_num,
      } = req.body

      // 检查考试是否存在
      const [exams] = await db.execute(
        'SELECT status FROM exams WHERE id = ?',
        [examId]
      )
      if (exams.length === 0) {
        return error(res, '考试不存在', 404)
      }

      // 检查考试状态
      if (exams[0].status === 'published') {
        return error(res, '已发布的考试无法修改题目', 400)
      }

      // 验证题目类型和选项
      if (
        ['single', 'multiple'].includes(type) &&
        (!options || options.length < 2)
      ) {
        return error(res, '选择题至少需要2个选项', 400)
      }

      const [result] = await db.execute(
        `
        INSERT INTO questions (exam_id, type, title, content, options, correct_answer, score, order_num) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
      `,
        [
          examId,
          type,
          title,
          content,
          JSON.stringify(options),
          correct_answer,
          score || 1,
          order_num || 0,
        ]
      )

      success(
        res,
        {
          id: result.insertId,
          examId,
          type,
          title,
          content,
          options,
          correct_answer,
          score,
          order_num,
        },
        '题目创建成功'
      )
    } catch (err) {
      next(err)
    }
  },

  // 更新题目
  async updateQuestion(req, res, next) {
    try {
      const { id } = req.params
      const {
        type,
        title,
        content,
        options,
        correct_answer,
        score,
        order_num,
      } = req.body

      // 检查题目是否存在
      const [questions] = await db.execute(
        `
        SELECT q.*, e.status as exam_status 
        FROM questions q 
        JOIN exams e ON q.exam_id = e.id 
        WHERE q.id = ?
      `,
        [id]
      )

      if (questions.length === 0) {
        return error(res, '题目不存在', 404)
      }

      // 检查考试状态
      if (questions[0].exam_status === 'published') {
        return error(res, '已发布的考试无法修改题目', 400)
      }

      const updateFields = []
      const updateValues = []

      if (type !== undefined) {
        updateFields.push('type = ?')
        updateValues.push(type)
      }
      if (title !== undefined) {
        updateFields.push('title = ?')
        updateValues.push(title)
      }
      if (content !== undefined) {
        updateFields.push('content = ?')
        updateValues.push(content)
      }
      if (options !== undefined) {
        updateFields.push('options = ?')
        updateValues.push(JSON.stringify(options))
      }
      if (correct_answer !== undefined) {
        updateFields.push('correct_answer = ?')
        updateValues.push(correct_answer)
      }
      if (score !== undefined) {
        updateFields.push('score = ?')
        updateValues.push(score)
      }
      if (order_num !== undefined) {
        updateFields.push('order_num = ?')
        updateValues.push(order_num)
      }

      if (updateFields.length === 0) {
        return error(res, '没有要更新的字段', 400)
      }

      updateValues.push(id)

      await db.execute(
        `
        UPDATE questions SET ${updateFields.join(', ')} WHERE id = ?
      `,
        updateValues
      )

      success(res, null, '题目更新成功')
    } catch (err) {
      next(err)
    }
  },

  // 删除题目
  async deleteQuestion(req, res, next) {
    try {
      const { id } = req.params

      // 检查题目是否存在及考试状态
      const [questions] = await db.execute(
        `
        SELECT q.*, e.status as exam_status 
        FROM questions q 
        JOIN exams e ON q.exam_id = e.id 
        WHERE q.id = ?
      `,
        [id]
      )

      if (questions.length === 0) {
        return error(res, '题目不存在', 404)
      }

      // 检查考试状态
      if (questions[0].exam_status === 'published') {
        return error(res, '已发布的考试无法删除题目', 400)
      }

      await db.execute('DELETE FROM questions WHERE id = ?', [id])

      success(res, null, '题目删除成功')
    } catch (err) {
      next(err)
    }
  },

  // 批量导入题目
  async importQuestions(req, res, next) {
    try {
      const { examId } = req.params
      const { questions } = req.body

      if (!Array.isArray(questions) || questions.length === 0) {
        return error(res, '请提供有效的题目数据', 400)
      }

      // 检查考试是否存在
      const [exams] = await db.execute(
        'SELECT status FROM exams WHERE id = ?',
        [examId]
      )
      if (exams.length === 0) {
        return error(res, '考试不存在', 404)
      }

      if (exams[0].status === 'published') {
        return error(res, '已发布的考试无法导入题目', 400)
      }

      const connection = await db.getConnection()
      await connection.beginTransaction()

      try {
        let successCount = 0

        for (const question of questions) {
          const { type, title, content, options, correct_answer, score } =
            question

          // 基本验证
          if (!type || !title) {
            continue
          }

          await connection.execute(
            `
            INSERT INTO questions (exam_id, type, title, content, options, correct_answer, score, order_num) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
          `,
            [
              examId,
              type,
              title,
              content || '',
              JSON.stringify(options || []),
              correct_answer || '',
              score || 1,
              successCount + 1,
            ]
          )

          successCount++
        }

        await connection.commit()
        success(
          res,
          { imported: successCount },
          `成功导入 ${successCount} 道题目`
        )
      } catch (importError) {
        await connection.rollback()
        throw importError
      } finally {
        connection.release()
      }
    } catch (err) {
      next(err)
    }
  },
}

module.exports = questionController
